<template>
	<view>
		<uni-file-picker :value="fileObjs" :limit="limit" :title="title" file-mediatype="image" @select="selectFile" @delete="deleteFile"></uni-file-picker>
	</view>
</template>

<script>
	export default {
		name: "upload",
		emits: ['success'],
		props: {
			url: {
				type: String,
				default: ''
			},
			limit: {
				type: Number,
				default: 9
			}
		},
		data() {
			return {
				fileObjs: [],
				title: '',
				uploadFiles: []
			};
		},
		watch: {
			url: {
				handler(val) {
					if (val) {
						var urls = val.split(',');
						this.fileObjs = []
						urls.forEach((item, index) => {
							if(item){
								var file = {
									name: item.substring(item.lastIndexOf("/")+1),
									extname: item.substring(item.lastIndexOf(".")+1),
									url: this.$util.showFile(item),
									id: item
								}
								this.fileObjs.push(file);
							}
						})
					}
				},
				deep: true
			}
		},
		mounted() {
			this.title = '最多选择'+this.limit+'张图片';
		},
		methods: {
			selectFile(e) {
				console.log(e);
				if(e.tempFilePaths){
					uni.showLoading({
						mask: true,
						title: '上传中...'
					})
					let tempFilePaths = e.tempFilePaths;
					var filePaths = new Array();
					tempFilePaths.forEach((item, index) => {
						this.$api.upload(item, 'image').then(res=>{
							filePaths.push(res.data);
							if(filePaths.length == tempFilePaths.length){
								uni.hideLoading();
								if(this.url){
									this.$emit('success',  this.url + ',' + filePaths.join());
								} else {
									this.$emit('success', filePaths.join());
								}
							}
						}).catch(err=>{
							uni.hideLoading();
						})
					})
				}
			},
			deleteFile(e){
				console.log(e);
				let fileId = e.tempFile.id;
				let filePaths = this.url.split(',');
				let i = 0;
				filePaths.forEach((item, index) => {
					if(item == fileId){
						i = index
					}
				})
				filePaths.splice(i, 1);
				this.$emit('success', filePaths.join());
			}
		}
	}
</script>
